﻿using System;
using System.Xml.Linq;
using System.Windows;
using SimpleCodeGenerator.Generators;
using System.Collections.Generic;
using SimpleCodeGenerator.Schema;
using SimpleCodeGenerator.Parsers;
using System.Reflection;
using System.IO;

namespace SimpleCodeGenerator
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnGenerate_Click(object sender, RoutedEventArgs e)
        {
            IParser parser = new PDMParser();
            string ns = txtNamespace.Text;
            if (!string.IsNullOrEmpty(ns))
            {
                if (!ns.StartsWith("."))
                {
                    ns = "." + ns;
                }
            }

            string mainDbSring = txtMainDBConnString.Text;
            string readonlyDbString = txtReadonlyDBConnString.Text;

            if (!string.IsNullOrEmpty(mainDbSring))
            {
                mainDbSring += ",";
            }

            if (!string.IsNullOrEmpty(readonlyDbString))
            {
                readonlyDbString += ",";
            }
            try
            {
            List<TableSchema> tables = parser.ParseFromFile(txtPDMPath.Text);
            foreach (var table in tables)
            {
                Generate(table, new ModelGenerator()
                {
                    Namespace = ns,
                    OutputPath = txtModelPath.Text,
                });
                Generate(table, new DataLayerGenerator()
                {
                    Namespace = ns,
                    OutputPath = txtDataLayerPath.Text,
                    MainDbConnString = mainDbSring,
                    ReadonlyDBConnString = readonlyDbString
                });
                Generate(table, new ServiceLayerGenerator()
                {
                    Namespace = ns,
                    OutputPath = txtServiceLayerPath.Text
                });
            }
            MessageBox.Show("生成成功，请打开文件夹查看");
            }
            catch (Exception ex)
            {
                File.WriteAllText(Directory.GetCurrentDirectory() + "/log.txt", ex.StackTrace);
                MessageBox.Show(ex.Message);
            }
        }

        private void Generate(TableSchema table, GeneratorBase generator)
        {
            generator.Generate(table);
        }
    }
}
